// const { Op } = require("sequelize");
const Merchandise = require("../model/Merchandise");
const { createStock } = require("./stockServer");
// const crypto = require("crypto");
// 添加商品
exports.addMerchandise = async function (Obj) {
  const ins = await Merchandise.create({
    createBy: Obj.createBy,
    name: Obj.name,
    // 价格
    price: +Obj.price,
    // 商品描述
    info: Obj.info,
    // 商品图片地址
    imgUrl: Obj.imgUrl,
  });
  // 创建库存
  await createStock({
    userId: Obj.createBy,
    merchandiseId: ins.id
  });
  console.log(ins.toJSON(), "添加成功");
  return ins.toJSON();
};
// 获取商品列表
exports.getMerchandise = async function (page = 1, limit = 10, keyword = "") {
  const where = {};
  if (keyword) {
    where.name = {
      [Op.like]: `%${keyword}%`,
    };
  }
  // 查询商品列表
  const res = await Merchandise.findAndCountAll({
    where,
    offset: (page - 1) * limit,
    limit: +limit,
  });
  return {
		total: res.count,
		data: JSON.parse(JSON.stringify(res.rows)),
	};
}

exports.deleteMerchandise = async function (merchandiseId) {
  // 检查商品是否存在
  const merchandise = await Merchandise.findByPk(merchandiseId);
  if (!merchandise) {
    throw '商品不存在'
  }
};